﻿using System;
using System.ComponentModel;
using System.Linq;
using Castle.Core.Interceptor;
using NHibernate.Validator.Engine;

namespace TestBat.Models.Interceptors.Domain
{
    public class DataErrorInfoInterceptor : Castle.Core.Interceptor.IInterceptor
    {
        public DataErrorInfoInterceptor(ValidatorEngine validatorEngine)
        {
            this.validatorEngine = validatorEngine;
        }

        public void Intercept(IInvocation invocation)
        {
            if (invocation.Method.DeclaringType.Equals(typeof(IDataErrorInfo)))
            {
                if ("get_Item".Equals(invocation.Method.Name))
                {
                    string[] invalidvalues = validatorEngine.ValidatePropertyValue(invocation.Proxy, (string)invocation.Arguments[0])
                        .Select(iv => iv.Message)
                        .ToArray();

                    invocation.ReturnValue = string.Join(Environment.NewLine, invalidvalues);
                }
                else if ("get_Error".Equals(invocation.Method.Name))
                {
                    string[] invalidValues = validatorEngine.Validate(invocation.Proxy)
                        .Select(iv => iv.Message)
                        .ToArray();

                    invocation.ReturnValue = string.Join(Environment.NewLine, invalidValues);
                }
            }
            else
                invocation.Proceed();
        }

        protected readonly ValidatorEngine validatorEngine;
    }
}
